/*
 * Copyright (c) 2021 Zsj. All rights reserved.
 */

package com.jzz.crawlerweb.handler.util;

import com.jzz.crawlerweb.handler.config.CaptchaUrlMap;
import com.jzz.crawlerweb.handler.data.Captcha;
import com.jzz.crawlerweb.handler.props.CaptchaProps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Component
public class CaptchaUtil {

    @Autowired
    private CaptchaProps captchaProps;

    public Captcha getCaptcha(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String type = CaptchaUrlMap.getType(request.getServletPath());
        if (session.getAttribute(captchaProps.getParamName() + ":" + type) != null) {
            return Captcha.getInstance(type, session.getAttribute(captchaProps.getParamName() + ":" + type).toString());
        }
        return null;
    }

    public String getSecret(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return session.getAttribute("secret").toString();
    }

    public boolean verifySecret(HttpServletRequest request, String secret) {
        HttpSession session = request.getSession();
        return session.getAttribute("secret").toString().equals(secret);
    }
}
